<template>
    <div class="memberinfo-layout">
        <div class="info-back search-part">
            <el-row :gutter="20">
                <el-col :span="12">
                    <div class="back-icon" @click="back()">
                        <i class="fa fa-arrow-left" aria-hidden="true"></i>&nbsp;
                    </div>
                </el-col>
                <el-col :span="10" class="btns">
                    <el-button type="text" class="save red-btn" @click="onSubmit('formMember')">
                        保存
                    </el-button>
                </el-col>
            </el-row>
        </div>
        <div class="member-info-title">
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="会员信息" name="first">
                    <el-form :model="formMember" :rules="formMemberRules" label-width="100px" ref="formMember" class="member-info-form">
                        <el-form-item label="会员姓名:" prop="name"
                                      :rules="[
                              {
                                  required: true,
                                  message: '请输入会员姓名',
                                  trigger: 'change'
                              }
                            ]">
                            <el-input v-model="formMember.name"></el-input>
                        </el-form-item>
                        <el-form-item label="卡号:" prop="account"
                                      :rules="[
                              {
                                  required: true,
                                  message: '请输入卡号',
                                  trigger: 'change'
                              }
                            ]">
                            <el-input v-model="formMember.account"></el-input>
                        </el-form-item>
                        <el-form-item label="密码:" prop="password">
                            <el-input  type="password" name="password" v-model="formMember.password" placeholder="*** ***" autocomplete="new-password"  auto-complete="new-password"></el-input>
                        </el-form-item>
                        <el-form-item
                                label="电话:"
                                prop="tel"
                                :rules="[
                                    {
                                        pattern: /^[1]\d{10}$/,
                                        message: '请输入正确的电话号码',
                                        trigger: 'change'
                                    }
                                  ]">
                            <el-input v-model="formMember.tel"></el-input>
                        </el-form-item>
                        <el-form-item
                                label="邮箱:"
                                prop="email"
                                :rules="[
                                    { type: 'email', message: '请输入正确的邮箱', trigger: 'change' }
                                ]">
                            <el-input v-model="formMember.email"></el-input>
                        </el-form-item>
                        <el-form-item label="住址:" prop="address">
                            <el-input v-model="formMember.address"></el-input>
                        </el-form-item>
                        <el-form-item label="状态" prop="state">
                            <div class="el-left">
                                <el-switch on-text="启用"
                                           off-text=""
                                           v-model="status"
                                           on-color="#13ce66"
                                           off-color="#cacaca"
                                ></el-switch>
                            </div>
                        </el-form-item>
                        <el-form-item label="建档时间:" prop="createTime">
                            <el-input v-model="formMember.createTime" :disabled="true"></el-input>
                        </el-form-item>
                        <el-form-item label="备注:" prop="remark" class="member-mark">
                            <el-input type="textarea" v-model="formMember.remark"></el-input>
                        </el-form-item>
                        <el-form-item label="上传图片" prop="upload" class="member-upload">
                            <div class="el-left">
                                <el-upload
                                        class="avatar-uploader"
                                        :action="uploadUrl"
                                        :show-file-list="false"
                                        :on-success="handleAvatarSuccess"
                                        :before-upload="beforeAvatarUpload"
                                        :on-error="onError">
                                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                                </el-upload>
                            </div>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="已购商品" name="second" v-if="activate">
                    <div class="goods-layout purchase-last">
                        <el-row :gutter="20">
                            <div class="purchase" v-for="(item, index) in goodItems">
                                <el-col :span="4">
                                    <div class="purchase-img">
                                        <img v-if="item.goods.pictureName" :src="item.goods.pictureName" class="avatar">
                                        <img v-else src="../../../../static/img/goods.png" >
                                    </div>
                                </el-col>
                                <el-col :span="7" class="purchase-con" style="padding-top: 10px">
                                    <span>{{ item.goodsName }}：<i class="purchase-num">{{ Number(item.quantity).toFixed(2) }}</i>{{item.goods.unit}}</span>
                                    <span>价值：<i >{{ Number(item.realPrice || 0).toFixed(2) }}</i>元</span>
                                </el-col>
                                <el-col :span="3">
                                </el-col>
                            </div>
                        </el-row>
                    </div>

                </el-tab-pane>
                <el-tab-pane label="交易记录" name="third" v-if="activate">
                    <div class="list">
                        <div v-for="(item, index) in allItems"  class="commission-list">
                            <div class="grid-content bor-radius-10 mg-bo-10 pos-relative">
                                <div class="card-01">
                                    <el-row :gutter="20">
                                        <el-col :span="4">
                                            <div class="grid-content pd">
                                                <img v-if="item.goodsPicturesName" :src="static_url + item.goodsPicturesName">
                                                <img v-else src="../../../../static/img/goods.png">

                                            </div>
                                        </el-col>
                                        <el-col :span="20">
                                            <div class="grid-content text">
                                                <el-row :gutter="20">
                                                    <el-col :span="12">
                                                        <div class="grid-content bg-purple goods-name">
                                                            {{item.goods_name}}
                                                        </div>
                                                    </el-col>
                                                    <el-col :span="12">
                                                        <div class="grid-content bg-purple">
                                                            {{item.bizdate}}
                                                        </div>
                                                    </el-col>
                                                </el-row>

                                                <el-row :gutter="20">
                                                    <el-col :span="8">
                                                        <div class="grid-content bg-purple">
                                                            数量：{{item.quantity}}
                                                    </div>
                                                    </el-col>
                                                    <el-col :span="8">
                                                        <div class="grid-content bg-purple">
                                                            应收:<span class="consume">{{Number(item.receivable || 0).toFixed(2)}}</span>
                                                        </div>
                                                    </el-col>
                                                    <el-col :span="8">
                                                        <div class="grid-content bg-purple">
                                                            实收：<span class="consume">{{Number(item.amount || 0).toFixed(2)}}</span>
                                                        </div>
                                                    </el-col>
                                                </el-row>

                                                <p class="l2">
                                                    <span>支付方式：{{item.payment}}</span>
                                                </p>

                                            </div>
                                        </el-col>
                                    </el-row>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>

<script>
    import * as type from '../../../store/types';
    export default {
        data: function () {
            return {
                imageUrl: '',
                uploadUrl: this.$cfg.api_url + "/vue-uploads",
                activeName: 'first',
                isMultiselect: true,
                userId: '',
                formMember: {},
                goodItems: '',
                status: true,
                state: '',
                formMemberRules: {},
                activate: false,
                rows: 20,//显示数量
                page: 1,//当前页数
                totalPage: 1,//总页数
                allItems:[],
                items:[],
                currentUser:{},
            }
        },
        mounted: function () {
//            this.currentUser = JSON.parse(localStorage.getItem("currentUser"));
            this.$$("#content").scrollTop(0)
//            let self = this;
//            this.$$("#content").on('scroll', function (e) {
//                var scrollTop = self.$$("#content").scrollTop();
//                var innerHeight = self.$$("#content").innerHeight();
//                var scrollHeight = self.$$("#content").scrollHeight();
//                if (scrollTop + innerHeight >= scrollHeight) {
//                    self.page++;
//                    if (self.page > self.totalPage) {
//                        return;
//                    }
//                    self.loading = true;
//                    self.loadMore();
//                    console.log('*(******************' + self.page)
//                }
//            });
//
//            document.getElementById("myDIV").addEventListener('wheel', function (e) {
//                if (e.wheelDelta < 0 && self.$$("#content").scrollTop() === 0) {
//                    console.log(e.wheelDelta < 0 && self.$$("#content").scrollTop() === 0)
//                    self.page++;
//                    self.loading = true;
//                    self.loadMore();
//                }
//            });
            this.$$(window).resize();
        },
        activated: function () {
            this.$$("#content").scrollTop(0)
            this.currentUser = JSON.parse(localStorage.getItem("currentUser"));
            console.log(this.currentUser)
            let backInfo = this.$route.params;
            if (backInfo.item) {
                this.activate = true;
                this.userId = backInfo.item.id;
                this.formMember = backInfo.item;
                if(this.formMember.portraitName){
                    this.imageUrl = this.$cfg.static_url + "/" + this.formMember.portraitName;
                }else{
                    this.imageUrl =''
                }
                console.log( this.imageUrl )
                if (this.formMember.state == 1) {
                    this.status = true;
                } else {
                    this.status = false;
                }
                let self = this;
                this.$axioxs.get('/goods_paid/?userId=' + this.userId)
                    .then(function (res) {
                        self.goodItems = res.data.records;
                    })
            }
            else {
                this.activate = false;
                this.activeName = 'first';
                this.formMember = {
                    name: '',
                    account: '',
                    password:'',
                    tel: '',
                    email: '',
                    createTime: '',
                    address: '',
                    remark: '',
                    imageUrl: ''
                };
                this.status=true;
                this.imageUrl = '';
                let self=this;
                this.$axioxs.get('/sn/?key=account&organId='+'c5fe00d4-03ff-45b0-8aa3-bb9c4558427c').then(function (res) {
                    self.$set(self.formMember,'account',res.data);
                })
            }

        },
        methods: {

            handleClick(tab, event) {
                if (this.activeName == 'first') {}
                else if (this.activeName == 'second') {
                    this.page=1;
                    let self=this;
                    this.$axioxs({
                        method: 'get',
                        url: '/goods_paid/?userId='+ this.formMember.id + "&rows=" + this.rows + "&page=" + this.page
                    })
                        .then(function (res) {
                            console.log(res.data)
                            self.totalPage = res.data.totalPage;
                            self.goodItems = res.data.records;
                            self.goodItems.forEach(item => {
                                item.height = 265;
                                item.width = 300;
                                self.items.push(item);
                            });

                        })
                        .catch(function (error) {
                            console.log(error);
                            self.$message({
                                showClose: true,
                                type: 'error',
                                message: error
                            });
                        });
                } else if (this.activeName == 'third') {
                    this.page=1
                    let self=this;
                    this.$axioxs({
                        method: 'get',
                        url: '/goods_paid/reserved_goods?type=30&memberId='+ this.formMember.id + "&rows=" + this.rows + "&page=" + this.page
                    })
                        .then(function (res) {
                            console.log(res.data)
                            self.totalPage = res.data.totalPage;
                            self.allItems = res.data.records;
                            self.allItems.forEach(item => {
                                item.height = 265;
                                item.width = 300;
                                self.items.push(item);
                            });

                        })
                        .catch(function (error) {
                            console.log(error);
                            self.$message({
                                showClose: true,
                                type: 'error',
                                message: error
                            });
                        });
                }
            },
            onSubmit(formName) {
              let hasRights = this.currentUser.rights.find(obj=> obj === 'member_add')
              if(hasRights != 'member_add'){
                this.$message({
                    showClose: true,
                    message: '权限不足',
                    type: 'warning'
                });
                return;
              }
                this.$refs[formName].validate((valid) => {
                    if (valid) {

                        let args = this.formMember;
                        args.kindCode = 20;
                        args.password = this.formMember.password||'';
                        if (this.status == true) {
                            args.state = 1;
                        } else {
                            args.state = 0;
                        }
                        if(this.$route.params.new){
                            args.password =this.formMember.password||'123456';
                        }else{
                            args.password =this.formMember.password||"";
                        }
                        let self = this;
                        this.$axioxs.post("/user/", args)
                            .then(function (res) {
                                console.log(JSON.stringify(res.data));
                                self.loading = false;
                                self.back();
                            })
                            .catch(function (error) {
                                console.log(error);
                                self.$message({
                                    showClose: true,
                                    type: 'error',
                                    message: error,
                                    onClose: function () {
                                        self.loading = false;
                                    }
                                });
                            });
                    }
                });
//
            },
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
                if (res && res.length > 0) {
                    this.formMember.portraitId = res[0].id;//将图片实例ID保存在FORM中
                }
                console.log(res)
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            onError: function (err, file, fileList) {
                alert(err)
            },
            back: function () {
                this.$store.commit(type.CHANGE_INDEX, '/membermanage');
                this.activeName = "first";
                this.$router.push('/membermanage');
            },
        }

    }
</script>

<style scoped>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }

    .avatar-uploader .el-upload:hover {
        border-color: #20a0ff;
    }

    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }

    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }

    .el-row {
        margin-bottom: 0;
    }

    .member-info-form {
        width: 90%;
        padding-top: 0px;
        margin: 0 auto;
    }
    .member-info-title{
        padding-top: 60px;
    }
    .purchase-img{
        width: 80px;
        height:80px;
        margin-left: 10px;
        margin-top: 8px;
    }
    .purchase-img img{
        width: 100%;
        height: 100%;
    }
    .commission-list{
        margin-top: 5px;
        padding: 20px 10px 0 10px;
        border-bottom: 1px solid #cacaca;
    }
    .consume{
        color: #fb0b18;
        font-size: 1.2em;
    }
    /*.onClass{*/

    /*}*/
    /*.offClass{*/

    /*}*/
</style>
